<template>
  <div class="login-box">
    <transition name="fade">
      <div class="login-content" v-if="isShow">
        <div class="login-title">
          <p>OBT</p>
          <span>下应用，看精华，尽在OBT</span>
        </div>
        <!-- <van-field
          class="input-box"
          v-model="form.username"
          type="number"
          @change="uem=''"
          placeholder="请输入手机号"
          :error-message="uem"
        /> -->
        <van-field
          class="input-box"
          v-model="form.username"
          @change="uem=''"
          placeholder="请输入用户名"
          :error-message="uem"
        />

        <van-field
          class="input-box"
          v-model="form.password"
          @change="pem=''"
          :type="togglePassword?'text':'password'"
          placeholder="请输入密码"
          :error-message="pem"
          @click-icon="togglePassword=!togglePassword"
        >
          <img
            slot="icon"
            v-if="form.password"
            :src="togglePassword?'static/img/login-visible.png':'static/img/login-invisible.png'"
            style="width: 24px;"
          />
        </van-field>
				<div style="position:relative;float:right;display:none">
<!--					<span>打开摄像头，扫描邀请二维码:</span>-->
					<span class="sweep" >扫码注册</span>
          <div class="picupload" v-if="isIos">
            <van-uploader :after-read="onRead" result-type="text" accept="image/*" multiple>
            </van-uploader>
          </div>
					<input type="file" v-if="isAndroid" id="file" class="get-camera" @change="getImage" accept="image/*">
				</div>
        <van-button type="" class="loginBit" size="large" :disabled="logDis" @click="login">登 录</van-button>
        <div class='loading-box'>
          <van-loading v-if="loadingControl" type="spinner" color="black" />
        </div>
        <div class="">
          <span class="login-text" @click="goIndex">免登录</span>
          <span class="login-text" @click="goRegist">去注册</span>
          <span class="login-text" @click="goForgetPassword">忘记密码</span>
        </div>

      </div>
    </transition>
  </div>

</template>

<script>

  import { Toast,Loading} from 'vant';
  import Cookies from 'js-cookie'
  export default {
    components: {
    },
    data() {
      return {
        isShow: false,
        logDis:false,//登录按钮节流
        togglePassword: false,
        uem: "",
        pem: "",
        file:[],
        form: {
          username: '',
          password: ''
        },
           //  版本参数
        param_uuid:null,
        loadingControl:false,

        param_scource:null,
        isIos:true,
        isAndroid:true
      }
    },
    created() {
      //获取设备注册信息
      var Device_uuid = sessionStorage.getItem('Device_uuid');

      if(Device_uuid){

        this.param_uuid = sessionStorage.getItem('Device_uuid');
      }else{

        //获取uuid参数
        this.param_uuid = this.uuid();
        sessionStorage.setItem('Device_uuid',this.param_uuid );
      }
    },
    mounted() {
      if(this.andOrIos()) { //android
        this.isIos = false;
        this.isAndroid = true;
      }else{
        this.isIos = true;
        this.isAndroid = false;
      }
      this.isShow = true;
      active_g = 5;
      window.onload = () => {
			  document.addEventListener('touchstart', (event) => {
			    if (event.touches.length > 1) {
			       event.preventDefault();
			    }
			  }, { passive: false });

			  let lastTouchEnd = 0;
			  document.addEventListener('touchend', (event) => {
			    const now = (new Date()).getTime();
			    if (now - lastTouchEnd <= 300) {
			      event.preventDefault();
			    }
			    lastTouchEnd = now;
			  }, false);
			}
      // 键盘弹出遮挡问题
      if(/Android [4-6]/.test(navigator.appVersion)) {
        window.addEventListener("resize", function() {
          if(document.activeElement.tagName=="INPUT" || document.activeElement.tagName=="TEXTAREA") {
            window.setTimeout(function() {
              document.activeElement.scrollIntoViewIfNeeded();
              $('body').css({
                'height':$(window).height()
              })
            }, 0);
          }
        })
      }
    },

    methods: {
      goIndex(){
         this.$router.push('/index');
      },
      goRegist(){
         this.$router.push('/regist?userid=islogin');
      },
      goForgetPassword(){
         this.$router.push('/rePassword');
      },
      onRead(file) {
        var $this = this;
        if(file.length > 1){
          file.map(function(item,index){
            $this.file.push(item.file);
          })
        }else{
          $this.file.push(file.file);
        }
        let formData = new FormData();
        formData.append('img_file', $this.file[0]);
        $this.loadingControl = true;
        $this.$axios.post(url_g+"/qrdecode/",formData
        ).then((res)=>{
          $this.file = [];
          $this.loadingControl = false;
          if(res && res.data && res.data.content && res.data.content.indexOf('http') != -1){
            window.open(res.data.content)
          }else{
            this.toast =  Toast('请选择邀请的二维码图片');
          }
        }).catch((e)=>{
          $this.loadingControl = false;
          $this.file = [];
          this.toast =  Toast('请选择邀请的二维码图片');
        })
      },
      getImage(){
        var $this = this;
        let fileInput = document.getElementById('file')
        for(let i = 0; i < fileInput.files.length;i++){
          this.file.push(fileInput.files[i])
        }
        let formData = new FormData();
        formData.append('img_file', $this.file[0]);
        $this.loadingControl = true;
        $this.$axios.post(url_g+"/qrdecode/",formData
        ).then((res)=>{

          $this.file = [];
          $this.loadingControl = false;
          if(res && res.data && res.data.content && res.data.content.indexOf('http') != -1){
            window.open(res.data.content)
          }else{
            this.toast =  Toast('请选择邀请的二维码图片');
          }
        }).catch((e)=>{
          $this.loadingControl = false;
          $this.file = [];
          this.toast =  Toast('请选择邀请的二维码图片');
        })
      },
      login() {
        this.logDis = true;
        // if(this.form.username && (/^1[34578]\d{9}$/.test(this.form.username)) && this.form.password){
        if(this.form.username && this.form.password){
          this.$axios({
            method: "POST",
            data: 'user_name='+this.form.username+'&password='+this.form.password,
            url: url_g+"/login/"
          }).then((res) => {
            console.log(res)
            this.logDis = false;
            sessionStorage.setItem("usermessage",JSON.stringify(res.data));
            sessionStorage.setItem("ji_status",JSON.stringify(res.data.user.status));
            token_g = JSON.parse(sessionStorage.getItem("usermessage")).token;
            Cookies.set('token',token_g)
            //
            this.$router.push('/game')
          }).catch((e)=>{
            this.logDis = false;
            Toast(e.response.data.detail);
          })
        }else{
          this.logDis = false;
          this.toast =  Toast('请输入完整的正确信息');
        }

      },
      andOrIos() {
        let u = navigator.userAgent;
        let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        return isAndroid
      },
      //  判断手机来源
      ismobile(test){
        var u = navigator.userAgent, app = navigator.appVersion;
        if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))){
          if(window.location.href.indexOf("?mobile")<0){
            try{
              if(/iPhone|mac|iPod|iPad/i.test(navigator.userAgent)){
                return 1;
              }else{
                return 0;

              }
            }catch(e){
            }
          }
        }else if( u.indexOf('iPad') > -1){
          return 0;

        }else{
          return 1;
        }
      },
      //获取手机唯一标志符
      uuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");

        return uuid;
      },
    }
  }
</script>

<style scoped="scoped">
  .login-text{
    float:right;
    color:#fff;
    margin-top:10px;
    margin-left:20px;
  }
  input{
    color:#fff
  }
  .loading-box{
    position:absolute;
    top: 25%;
    left: 46%;
  }
	.get-camera{
		opacity:0;
		z-index:9999999;
		margin-top:30px;
		width:100px;
		margin-left:20px
	}
	.sweep{
		position: absolute;
    right: -20px;
		top: 30px;
		z-index: 0;
		width: 100px;
		text-align: center;
		/*background-color: #025596;*/
  	/*border: 1px solid #025596;*/
  	border-radius: 5px;
  	color: #fff;
  	height: 28px;
  	line-height: 28px;
    font-size: 14px;
	}
  .login-box {
    height: 100vh;
    box-sizing: border-box;
    padding: 65px 12px 0;
    background: -moz-linear-gradient( top,#028aed,#273eec);
    background: -webkit-linear-gradient( top,#028aed,#273eec);
  }

  h3 {
    /*text-align: center;*/
    margin-bottom: 76px;
  }

  button {
    margin-top: 30px;
  }
  .fade-enter-active {
    -webkit-transition: all .5s;
    transition: all .5s;
  }
  .van-cell-group{
    background-color:transparent
  }
  .van-hairline--top-bottom::after{
    border-top:0px
  }
  .login-content{
    width:80%;
    margin:0 auto
  }
  .picupload{
    height: 30px;
    margin-top: 30px;
    margin-left: 20px;
    width: 100px;
  }
  .van-cell{
    background-color:transparent !important
  }
  .van-hairline--top-bottom::after{
    border-color:#fff;
  }
  .van-cell:not(:last-child)::after{
    border-color:#fff;
  }
  [class*=van-hairline]::after{
    margin-left:15px;
  }
  .loginBit{
    background-color:#fff;
    border-radius:50px;
    border-width:0;
    color:#23accd
  }
  .input-box{
    color:#fff;
  }
  .login-box .van-cell__value{
    width:100%
  }
  .login-title {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 60px;
  }
  .login-title p {
    color: #fff;
    font-size: 40px;
    margin: 0;
    line-height: 60px;
  }
  .login-title span {
    color: rgba(255,255,255,0.8);
    font-size: 14px;
  }
</style>